package com.cardbaobao.cardbabyclient.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.BuildConfig;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.controller.BroadcastController;
import com.cardbaobao.cardbabyclient.ui.activity.AccountLoginActivity;
import com.cardbaobao.cardbabyclient.ui.activity.ApplyRecordActivity;
import com.cardbaobao.cardbabyclient.ui.activity.BankCardManageActivity;
import com.cardbaobao.cardbabyclient.ui.activity.FeedbackActivity;
import com.cardbaobao.cardbabyclient.ui.activity.MyCollectActivity;
import com.cardbaobao.cardbabyclient.ui.activity.AvatarNickNameActivity;
import com.cardbaobao.cardbabyclient.ui.activity.RealNameAuthenticationActivity;
import com.cardbaobao.cardbabyclient.ui.activity.RealNamePassActivity;
import com.cardbaobao.cardbabyclient.ui.activity.SettingActivity;
import com.cardbaobao.cardbabyclient.ui.activity.TransactionRecordActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.controller.IntentConstant;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.ui.activity.MineMessageActivity;
import com.cardbaobao.cardbabyclient.model.Event;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.ShareUtil;
import com.cardbaobao.cardbabyclient.utils.SharedPreferencesUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.BottomPopupOption;
import com.cardbaobao.cardbabyclient.widget.IntentionLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;

/**
 * Description:
 * Created by FHW
 * on 2017/6/14
 */

public class MineFragment extends BaseFragment {
    private String prePageId;
    public void setBuriedInfo(String prePageId){
        this.prePageId=prePageId;
    }
    public static final int LoginCode = 1001;

    @BindView(R.id.user_avatar)
    CircleImageView user_avatar;

    @BindView(R.id.il_identify_verify)
    IntentionLayout ilIdentifyVerify;//身份认证

    @BindView(R.id.user_name)
    TextView user_name;//用户名称

    @BindView(R.id.v_api_address_divider)
    View apiAddressDivider;
    @BindView(R.id.il_api_address_switch)
    IntentionLayout ilApiAddressSwitch;

    private Class<?> toActivity = null;

    private BroadcastReceiver mLoginBroadcastReceiver;

    private BottomPopupOption bottomPopupOption;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initIntent();

        //如果不是生产环境，显示切换api地址环境布局
        if(!Constant.PRODUCT_ENVIRONMENT.equals(BuildConfig.BUILD_TYPE)) {
            apiAddressDivider.setVisibility(View.VISIBLE);
            ilApiAddressSwitch.setVisibility(View.VISIBLE);
            switch (SharedPreferencesUtil.ConfigInfo.getApiAddressType()) {
                case 1:
                    ilApiAddressSwitch.setTextRight("测试环境(21)");
                    break;
                case 2:
                    ilApiAddressSwitch.setTextRight("测试环境(22)");
                    break;
                case 3:
                    ilApiAddressSwitch.setTextRight("灰度环境");
                    break;
                case 4:
                    ilApiAddressSwitch.setTextRight("生产环境");
                    break;
                default:
                    ilApiAddressSwitch.setTextRight("开发环境");
                    break;
            }
        }

        mCurrentPageId= Self.Page.app_mine_index_page;

        IntentFilter intentFilter = new IntentFilter(IntentConstant.Action.BROADCAST_LOGIN_ACTION);
        mLoginBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                initLoginView();
            }
        };
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mLoginBroadcastReceiver, intentFilter);

        bottomPopupOption = new BottomPopupOption(getActivity());
        bottomPopupOption.setItemClickListener(new BottomPopupOption.onPopupWindowItemClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    case 0:
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_index_invite_friend_wx,
                                Self.Action.app_click_mine_index_invite_friend_wx_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        ShareUtil.toShare(getActivity(), ShareUtil.SHARE_MEDIA_LIST[0]);
                        break;
                    case 1:
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_index_invite_friend_wx_circle,
                                Self.Action.app_click_mine_index_invite_friend_wx_circle_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        ShareUtil.toShare(getActivity(), ShareUtil.SHARE_MEDIA_LIST[1]);
                        break;
                    case 2:
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_index_invite_friend_sina,
                                Self.Action.app_click_mine_index_invite_friend_sina_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        ShareUtil.toShare(getActivity(), ShareUtil.SHARE_MEDIA_LIST[2]);
                        break;
                    case 3:
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_index_invite_friend_qq,
                                Self.Action.app_click_mine_index_invite_friend_qq_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        ShareUtil.toShare(getActivity(), ShareUtil.SHARE_MEDIA_LIST[3]);
                        break;
                }
                bottomPopupOption.dismiss();
            }
        });

    }


    private void getUserInfo(){
        //获取用户信息
        showProgressDialog(true);
        Api.getUserInfo(String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        JSONObject object= JSON.parseObject(s);
                        if(object!=null&&object.getIntValue("code")==1){
                            UserInfo userInfo =
                                    JSON.parseObject(object.getJSONObject("msg").getString("data"),
                                            UserInfo.class);
                            if (userInfo != null) {
                                userInfo.setPhone(mApplication.getUser().getPhone());
                                mApplication.setUser(userInfo);
                                new BroadcastController(mContext).notifyUserLogin();
                                setIdentifyUi();
                            }
                        }
                    }
                });
    }


    //设置用户信息
    private void initLoginView() {
        //fragment生命周期回调时会调用到，此处要做空判断
        if (user_avatar == null || user_name == null) return;
        if (mApplication.getIsLogin() && mApplication.getUser() != null) {
            UserInfo userInfo = mApplication.getUser();
            ImageLoaderUtil.displayImageWithPlaceHolder(
                    URLUtil.CBB_IMG_URL + userInfo.getHeadImages(),
                    user_avatar,
                    R.mipmap.img_default_avatar);
            user_name.setText(userInfo.getUserName());
        } else {
            user_avatar.setImageResource(R.mipmap.img_default_avatar);
            user_name.setText("请点击登录");
        }
    }


    @OnClick({R.id.user_avatar,R.id.iv_setting,R.id.rl_news,
            R.id.il_identify_verify,
            R.id.il_transaction_record,R.id.il_apply_record,R.id.il_bank_card,
            R.id.il_my_collect,R.id.il_invitation_friends,R.id.il_feed_back,R.id.il_about_we,R.id.il_api_address_switch})
    public void onClick(View v) {
        mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
        switch (v.getId()) {
            case R.id.user_avatar:
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_set_personal_info,
                        Self.Action.app_click_mine_index_set_personal_info_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, AvatarNickNameActivity.class);
                toActivity = AvatarNickNameActivity.class;
                startLoginActivity(Constant.PLY010213);
                break;
            case R.id.iv_setting:
                //设置
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_setting,
                        Self.Action.app_click_mine_index_setting_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, SettingActivity.class);
                toActivity = SettingActivity.class;
                startLoginActivity(Constant.PLY010214);
                break;
            case R.id.rl_news://消息
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_msg_center,
                        Self.Action.app_click_mine_index_msg_center_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, MineMessageActivity.class);
                toActivity = MineMessageActivity.class;
                startActivity(mIntent);
                break;
            case R.id.il_identify_verify:
                //身份认证
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_identify_verify,
                        Self.Action.app_click_mine_index_identify_verify_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                if(mApplication.getIsLogin()){
                    UserInfo userInfo=mApplication.getUser();
                    if(!TextUtils.isEmpty(userInfo.getTrueName())&&!TextUtils.isEmpty(userInfo.getIDCardNo())){
                        mIntent.setClass(mContext, RealNamePassActivity.class);
                    }else{
                        mIntent.setClass(mContext, RealNameAuthenticationActivity.class);
                        mIntent.putExtra(RealNameAuthenticationActivity.GO_RESULT_ACTIVITY_B,true);
                    }
                    startActivity(mIntent);
                }else{
                    toActivity=null;
                    mIntent.setClass(mContext,AccountLoginActivity.class);
                    mIntent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                            Constant.PLY010212);
                    startActivity(mIntent);
                }
                break;
            case R.id.il_transaction_record:
                //交易记录
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_transaction_record,
                        Self.Action.app_click_mine_index_transaction_record_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, TransactionRecordActivity.class);
                toActivity=TransactionRecordActivity.class;
                startLoginActivity(Constant.PLY010222);
                break;
            case R.id.il_apply_record://申请记录
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_apply_record,
                        Self.Action.app_click_mine_index_apply_record_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, ApplyRecordActivity.class);
                toActivity = ApplyRecordActivity.class;
                startLoginActivity(Constant.PLY010215);
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, "我的-申请纪录");
                break;
            case R.id.il_bank_card:
                //银行卡
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_bank_card,
                        Self.Action.app_click_mine_index_bank_card_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, BankCardManageActivity.class);
                toActivity=BankCardManageActivity.class;
                startLoginActivity(Constant.PLY010216);
                break;
            case R.id.il_my_collect://收藏
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_collect,
                        Self.Action.app_click_mine_index_collect_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, MyCollectActivity.class);
                toActivity = MyCollectActivity.class;
                startLoginActivity(Constant.PLY010217);
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, "我的-我的收藏");
                break;
            case R.id.il_invitation_friends://邀请好友
                UmengEventUtils.pageEvent(mContext,
                        ApplicationHelper.getApplicationContext().getString(R.string.event_0x022));
                bottomPopupOption.showPopupWindow();
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, "我的-邀请好友");
                break;
            case R.id.il_feed_back://意见反馈
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_feedback,
                        Self.Action.app_click_mine_index_feedback_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext,FeedbackActivity.class);
                mContext.startActivity(mIntent);
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, "我的-意见反馈");
                break;
            case R.id.il_about_we://关于我们
                UmengEventUtils.pageEvent(mContext,
                        ApplicationHelper.getApplicationContext().getString(R.string.event_0x026));
                SelfUtils.buriedClickData(Self.Action.app_click_mine_index_about_us,
                        Self.Action.app_click_mine_index_about_us_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        prePageId);
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "关于我们");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S, URLUtil.ABOUT_US);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 7);
                mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                mContext.startActivity(mIntent);
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, "我的-关于我们");
                break;
            case R.id.il_api_address_switch://切换测试地址
                final String[] items=new String[]{"测试环境(21)","测试环境(22)","灰度环境","生产环境"};
                AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
                builder.setTitle("选择测试环境");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //如果选择的测试环境与目前所用的测试环境是一样的，不处理
                        //否则保存选择的测试环境，提示重启app
                        int select=which+1;
                        if(SharedPreferencesUtil.ConfigInfo.getApiAddressType()!=select){
                            SharedPreferencesUtil.ConfigInfo.setApiAddressType(select);
                            //显示测试环境
                            ilApiAddressSwitch.setTextRight(items[which]);
                            //退出登录状态
                            mApplication.clearUser();
                            ToastUtil.showToastLong("切换成功，重新打开App即可生效!");
                            getActivity().finish();
                            System.exit(0);
                        }
                    }
                });
                builder.show();
                break;
        }
    }

    private void startLoginActivity(String loginRequestFrom) {
        if (!mApplication.getIsLogin()) {
            mIntent.setClass(mContext, AccountLoginActivity.class);
            mIntent.putExtra(AccountLoginActivity.JUM_TYPE_I, 4);
            mIntent.putExtra(AccountLoginActivity.LOGIN_REQUEST_FROM_S,
                    loginRequestFrom);
            startActivityForResult(mIntent, LoginCode);
        } else {
            startActivity(mIntent);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mLoginBroadcastReceiver);
    }

    /**
     * 回调
     *
     * @param loginSucNotify
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.LoginSucNotify loginSucNotify) {
        if (loginSucNotify.getType() == 4) {
            if (toActivity != null) {
                mIntent.setClass(mContext, toActivity);
                startActivity(mIntent);
                toActivity = null;
            }
        }
        setIdentifyUi();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            GoogleAnalyticsUtil.setScreenName(Google.NEW_MINE);
            initLoginView();
            //如果用户已登录且未实名认证，重新获取数据
            UserInfo info=mApplication.getUser();
            if(info.getID()!=0){
                if(TextUtils.isEmpty(info.getTrueName())||TextUtils.isEmpty(info.getIDCardNo())){
                    getUserInfo();
                }else{
                    //已实名认证
                    if(ilIdentifyVerify!=null){
                        ilIdentifyVerify.setTextRightColor(0XFFFF9E27);
                        ilIdentifyVerify.setTextRight("已认证");
                    }
                }
            }else{
                if(ilIdentifyVerify!=null){
                    ilIdentifyVerify.setTextRightColor(0XFFDDDDDD);
                    ilIdentifyVerify.setTextRight("未认证");
                }
            }
        }
    }

    private synchronized void setIdentifyUi(){
        UserInfo userInfo=mApplication.getUser();
        if(!TextUtils.isEmpty(userInfo.getTrueName())&&!TextUtils.isEmpty(userInfo.getIDCardNo())){
            //已实名认证
            ilIdentifyVerify.setTextRightColor(0XFFFF9E27);
            ilIdentifyVerify.setTextRight("已认证");
        }else{
            //未实名认证
            ilIdentifyVerify.setTextRightColor(0XFFDDDDDD);
            ilIdentifyVerify.setTextRight("未认证");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initLoginView();
        setIdentifyUi();
    }
}
